<?php

namespace app\admin\middleware;
use app\common\exception\BaseException;
use app\admin\model\admin\User as UserModel;
class Auth
{
    public function handle($request, \Closure $next)
    {
        // 获取请求信息
        $http = [
            //控制器名称
            'controller' => $request->controller(),
            //方法名称
            'action' => $request->action(),
            'url' => $request->url(),
            'method' => $request->method(),
            'header' => $request->header(),
            'ip' => $request->ip(),
            'time' => time(),
            'date' => date('Y-m-d H:i:s'),
        ];

        //获取token
        $token = $request->header("token");
        if (empty($token)) {
            throw new BaseException(['msg' => '缺少必要的参数：token', 'code' => -1]);
        }
        $data = checkToken($token, 'admin');
        if ($data['code'] != 1) {
            throw new BaseException(['msg' => $data['msg'], 'code' => -1]);
        }
        if ($data['data']['type'] != 'admin') {
            throw new BaseException(['msg' => '用户信息错误', 'code' => -1]);
        }
        if (!$user = UserModel::getUser($data['data'])) {
            throw new BaseException(['msg' => '没有找到用户信息', 'code' => -1]);
        }

        //用户信息写入request
        $request->admin = $user;
        $request->http = $http;

        //返回
        return $next($request);
    }
}